import React, { Component } from 'react';
import ReacrDOM from 'react-dom'
import { Dialog, Grid, Input, Radio, Button,Form, Field, Feedback,Select } from '@icedesign/base';
import IceContainer from '@icedesign/container';
import axios from 'axios';
import {hashHistory} from 'react-router';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import { enquireScreen } from 'enquire-js';
import RolesTreeSelect from '../rolesSelect';
import {GET,POST,PUT} from '../../../../utils/public'


const { Row, Col } = Grid;
const { Group: RadioGroup } = Radio;
const FormItem = Form.Item;
const defaultValue = {
  keywords: '',
  type: 'post',
  content: '',
};

export default class EditDialog extends Component {
  static displayName = 'EditDialog';

  constructor(props) {
    super(props);
    this.field = new Field(this,{
      onChange:this.onFormChange
    });    
    this.state = {
      visible: false,
      value: defaultValue,
      isMobile: false,
      password:'',
      type:'',//dialog打开方式 edit 编辑， add 添加
      userID:null,
      dataSource:[],
      companyDataSource:[],
      roles:[],
      company:[],
    };
  }
  handleChildChange=(newState)=>{
    this.setState(newState)
    console.log(this.state.id)
  }

  componentDidMount() {
    this.enquireScreenRegister();
  }

  enquireScreenRegister = () => {
    const mediaCondition = 'only screen and (max-width: 720px)';

    enquireScreen((mobile) => {
      this.setState({
        isMobile: mobile,
      });
    }, mediaCondition);
  };

  onOpen=(record,type)=>{  
    console.log(record,type)
     //record: 编辑时record为当前行的数据记录，添加时为空
    //type: edit编辑 add 添加
    this.field.setValues({"loginName":"","mobile":"","name":"","password":"","roles":[],"company":[],"comment":""})
    this.setState({type,"userID":""})
    if(type=="edit"){
      //编辑用户时，回显数据
      this.setState({type,"userID":record.id})      
      let password = '!@#$%^&*()_+0';//要改成系统给用户默认的密码
      let roles1 = [];
      record.roles.map(item=>roles1.push(item.id)) ;//角色复显
      let company1 = [];
      record.companies.map(item=>company1.push(item.id))  //公司复显
      this.field.setValues({"loginName":record.loginName,"mobile":record.mobile,"name":record.loginName,"id":record.id,roles1,company1})
    }
    this.getRoleList();
    this.getCompanyList();
    
    this.showDialog();
  }
  getRoleList = () =>{
    GET(`api/roles?noPage=true`)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失联，稍后再试！')
        }else if(res.code==200 && res.success){
          let arr = [];
          res.data.map(item=>{
            arr.push({label:item.name,value:item.id})
          })
          this.setState({dataSource:arr})
        }
        
      })
  }
  getCompanyList = () =>{
    GET(`api/company?noPage=true`)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失联，稍后再试！')
        }else if(res.code==200 && res.success){
          let arr = [];
          res.data.map(item=>{
            arr.push({label:item.companyName,value:item.id})
          })
          this.setState({companyDataSource:arr})
        }
      })
  }

  showDialog = () => {   
    //显示dialog 
    this.setState({
      visible: true,
    });
  };

  hideDialog = () => {
    //隐藏dialog
    this.field.reset(); //关闭dialog时，清空field;
    this.setState({
      visible: false,
    });
  };
  onSubmit = () =>{
    //保存
    let type = this.state.type;
    (type === "edit")?(this.onEditSave()):(this.onAddSave());
  }

  onEditSave = () =>{
    //编辑保存
    let roles = this.state.roles;
    let company = this.state.company;
    this.field.setValues({roles,company})
    let id = this.state.userID;
    let data = this.field.getValues();
    PUT(`/api/users/${id}`,
      {
        loginName:data.loginName,
        mobile:data.mobile,
        name:data.name,
        companies:data.company,
        roles:data.roles,
        comment:data.comment
      }
    )
      .then(res=>{
        if(!res){
          Feedback.toast.error('网络错误，请稍后再试！')
          return;
        }else if(res.code==200 && res.success==true){
          Feedback.toast.success('保存成功')
          this.props.onSaveChange(true);
          this.hideDialog();
        }else if(res.code==400){
          this.resolveError(res.errors)
        }else if(res.code==401 && res.msg=='请登录!'){
          Feedback.toast.error(res.msg);
          setTimeout(()=>{
            window.location.href='#/Login'
          },500)
        }else{
          Feedback.toast.error(res.msg)
          return;
      }
      },error=>{
        Feedback.toast.error(error)
        return;
      })
   
  }

  onAddSave = () =>{
    //新增保存
    //校验
    this.field.validate((errors, values) => {
      if(errors){
        console.log(errors, values);
        return ;
      }
    });
    let roles = this.state.roles;
    let company = this.state.company;
    this.field.setValues({roles,company})
    let data = this.field.getValues();
    console.log(data)
    POST('/api/users',{
      loginName:data.loginName,
      password:data.password,
      mobile:data.mobile,
      name:data.name,
      companies:data.company,
      roles:data.roles,
      comment:data.comment
    })
      .then(res=>{
        if(!res){
          Feedback.toast.error('网络错误，请稍后再试！')
          return;
        }else if(res.code==200 && res.success==true){
          Feedback.toast.success('保存成功')
          this.props.onSaveChange(true);
          this.hideDialog();
      }else if(res.code==400){
        this.resolveError(res.errors)
      }else if(res.code==401 && res.msg=='请登录!'){
        Feedback.toast.error(res.msg);
        setTimeout(()=>{
          window.location.href='#/Login'
        },500)
      }else{
          Feedback.toast.error(res.msg)
          return;
      }
      },error=>{
        Feedback.toast.error(error)
        return;
      })

  }

  onFormChange = (name,value) => {
    let roles = value;
    let company = value;
    if(name== "roles1"){
      roles = roles.map(id=> Object({id}))
      this.setState({roles})
      console.log(value)
    }
    if(name=="company1"){
      company = company.map(id=> Object({id}))
      this.setState({company})
      console.log(value)
      
    }
  };
  resolveError=errors=>{
    //异常处理
    errors.forEach((item)=>{
      const { getError, setError, setErrors } = this.field;
      let name = item.field;
      let msg = item.message;
      setError(name, msg);
    })
  }


  render() {
    const { isMobile } = this.state;
    const simpleFormDialog = {
      ...styles.simpleFormDialog,
    };
    const formItemLayout = {
      labelCol: {
        fixedSpan: 10
      },
      wrapperCol: {
        span: 14
      }
    }
    const { init} = this.field;
    // 响应式处理
    if (isMobile) {
      simpleFormDialog.width = '300px';
    }

    return (
        <Dialog
          className="simple-form-dialog"
          style={simpleFormDialog}
          autoFocus={false}
          footerAlign="center"
          title="用户信息"
          {...this.props}
          onOk={this.onSubmit}
          onCancel={this.hideDialog}
          onClose={this.hideDialog}
          isFullScreen
          visible={this.state.visible}
        >
          <Form direction="ver" field={this.field}>
            <FormItem label="帐户名" {...formItemLayout} >
              <Input placeholder="" {...init("loginName" ,
                    { rules: [{ required: true,message: "不能为空" },
                    { min:2,max:20,message:'用户名2-20位'}]}
                    )}/>
            </FormItem >
            {(this.state.type=="edit")?
            (null)
            :( <FormItem label="密码" {...formItemLayout} >
            <Input placeholder=""  htmlType="password" minLength={5} maxLength={20}  {...init("password",
                  {rules:[ { required: true,message:"不能为空"},
                            { pattern: /^(?![^a-zA-Z]+$)(?!\D+$)/, message: '需要包含数字和字符' },
                            {min:5,max: 22,message:'密码5-22位！'}     
                          ]}
                        )} />
          </FormItem >)}
          <FormItem label="姓名" {...formItemLayout} >
              <Input placeholder="" {...init("name", { rules: [
                    { required: true,message: "不能为空" },
                    { min:2,max:20,message:'用户名2-20位'}]})}/>
            </FormItem >
            <FormItem label="手机号" {...formItemLayout} >
              <Input placeholder=""  {...init("mobile" ,
                    { rules: [{ required: true,message: "不能为空" },
                              { pattern:/^\d{11}$/,message:"11位手机号"},
                              {
                                validator: (rule, value, callback) => {
                                  callback();
                                }}
                            ]}
                      )}/>
            </FormItem >
            
            <FormItem label="所属公司" {...formItemLayout} >
              <Select 
                  {...init('company1',{ rules: [
                    { required: true,message: "不能为空" }]})}
                  dataSource={this.state.companyDataSource}
                  showSearch
                  hasClear
                  multiple={true}
                  style={{width:'100%'}}
                  />
            </FormItem>
            {/* <FormItem label="性别" {...formItemLayout} >
              <RadioGroup {...init("sex")}>
                  <Radio id="boy" value="1">
                    男
                  </Radio>
                  <Radio id="gril" value="2">
                    女
                  </Radio>
              </RadioGroup>
            </FormItem > */}
            <FormItem label="角色" {...formItemLayout} >
              <Select 
                 {...init('roles1')}
                  dataSource={this.state.dataSource}
                  showSearch
                  hasClear
                  multiple={true}
                  style={{width:'100%'}}
                  />
            </FormItem>
            
            <FormItem label="备注说明"  {...formItemLayout}>
              <Input multiple placeholder="" {...init("comment")} />
            </FormItem>
            </Form>
         </Dialog>
    );
  }
}

const styles = {
  simpleFormDialog: { width: '640px' },
  dialogContent: {},
  formRow: { marginTop: 20 },
  input: { width: '100%' },
  formLabel: { lineHeight: '26px' },
  formitem:{ visibility:"hidden",display:"none"}
};
